package com.xh.core.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.xh.core.bean.AjaxResult;
import com.xh.core.constant.AjaxResultConstant;
import com.xh.core.constant.XhMsgConstant;
import com.xh.core.util.CacheUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/*
 * @Author daiwei
 * @Description
 * @Date 2019/6/11 09:51
 **/
@RestController
@RequestMapping("/kaptcha")
public class KaptchaController {

    @Autowired
    private DefaultKaptcha kaptcha;

    @PostMapping("/render")
    public AjaxResult render() {
        try {
            Map<String, Object> map = new HashMap<>();
            // 生成文字验证码
            String text = kaptcha.createText();
            // 生成图片验证码
            ByteArrayOutputStream outputStream = null;
            BufferedImage image = kaptcha.createImage(text);
            outputStream = new ByteArrayOutputStream();
            ImageIO.write(image, "jpg", outputStream);
            //
            map.put("img", Base64.getEncoder().encodeToString(outputStream.toByteArray()));
            //生成验证码对应的token  以token为key  验证码为value存在redis中
            String codeToken = UUID.randomUUID().toString();

            CacheUtils.set(codeToken, text, 900);
            map.put("token", codeToken);
            return new AjaxResult(AjaxResultConstant.Result.SUCCESS,null,map);
        }catch (Exception ex){
            return new AjaxResult(AjaxResultConstant.Result.ERROR, XhMsgConstant.SYSTEM_ERROR_MSG);
        }
    }

    @PostMapping("/valid")
    public AjaxResult validDefaultTime(@RequestParam String token,@RequestParam String code) {
        boolean result=false;
        Object value = CacheUtils.get(token);
        if (value != null && code.equals(value)) {
            result= true;
        }
        return new AjaxResult(result,null);
    }
}
